// utils/util.js - 通用工具函数

/**
 * 格式化时间
 */
export function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  const d = new Date(date)
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化日期
 */
export function formatDate(date, separator = '-') {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  
  return `${year}${separator}${month}${separator}${day}`
}

/**
 * 相对时间格式化
 */
export function formatRelativeTime(date) {
  if (!date) return ''
  
  const now = new Date()
  const target = new Date(date)
  const diff = now - target
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else {
    return formatDate(date)
  }
}

/**
 * 防抖函数
 */
export function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 */
export function throttle(func, limit) {
  let lastFunc
  let lastRan
  return function executedFunction(...args) {
    if (!lastRan) {
      func(...args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(() => {
        if ((Date.now() - lastRan) >= limit) {
          func(...args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

/**
 * 生成随机字符串
 */
export function randomString(length = 8) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 深拷贝
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 对象数组去重
 */
export function uniqueArray(arr, key) {
  const seen = new Set()
  return arr.filter(item => {
    const value = key ? item[key] : item
    if (seen.has(value)) {
      return false
    }
    seen.add(value)
    return true
  })
}

/**
 * 手机号验证
 */
export function validatePhone(phone) {
  const phoneReg = /^1[3-9]\d{9}$/
  return phoneReg.test(phone)
}

/**
 * 身份证号验证
 */
export function validateIdCard(idCard) {
  const idCardReg = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/
  return idCardReg.test(idCard)
}

/**
 * 邮箱验证
 */
export function validateEmail(email) {
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailReg.test(email)
}

/**
 * 价格格式化
 */
export function formatPrice(price, currency = '¥') {
  if (isNaN(price)) return ''
  return `${currency}${Number(price).toFixed(2)}`
}

/**
 * 数字格式化（千分位）
 */
export function formatNumber(number) {
  if (isNaN(number)) return ''
  return Number(number).toLocaleString()
}

/**
 * 文件大小格式化
 */
export function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * URL参数解析
 */
export function parseUrlParams(url) {
  const params = {}
  const paramStr = url.split('?')[1]
  
  if (paramStr) {
    paramStr.split('&').forEach(param => {
      const [key, value] = param.split('=')
      params[decodeURIComponent(key)] = decodeURIComponent(value || '')
    })
  }
  
  return params
}

/**
 * 生成URL参数字符串
 */
export function buildUrlParams(params) {
  return Object.keys(params)
    .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
}

/**
 * 获取页面栈
 */
export function getCurrentPages() {
  return getCurrentPages()
}

/**
 * 获取当前页面路径
 */
export function getCurrentPagePath() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage ? currentPage.route : ''
}

/**
 * 安全导航（避免页面栈溢出）
 */
export function safeNavigate(options) {
  const pages = getCurrentPages()
  
  if (pages.length >= 10) {
    // 页面栈接近上限，使用redirectTo
    wx.redirectTo(options)
  } else {
    wx.navigateTo(options)
  }
}

/**
 * 预览图片
 */
export function previewImages(images, current = 0) {
  if (!Array.isArray(images) || images.length === 0) return
  
  wx.previewImage({
    urls: images,
    current: typeof current === 'number' ? images[current] : current
  })
}

/**
 * 保存图片到相册
 */
export function saveImageToPhotosAlbum(filePath) {
  return new Promise((resolve, reject) => {
    wx.saveImageToPhotosAlbum({
      filePath,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 复制到剪贴板
 */
export function copyToClipboard(text) {
  return new Promise((resolve, reject) => {
    wx.setClipboardData({
      data: String(text),
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        })
        resolve()
      },
      fail: reject
    })
  })
}

/**
 * 拨打电话
 */
export function makePhoneCall(phoneNumber) {
  wx.makePhoneCall({
    phoneNumber: String(phoneNumber)
  })
}

/**
 * 打开地图导航
 */
export function openLocation(latitude, longitude, name, address) {
  wx.openLocation({
    latitude: Number(latitude),
    longitude: Number(longitude),
    name: name || '目的地',
    address: address || ''
  })
}

/**
 * 获取设备信息
 */
export function getSystemInfo() {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 振动反馈
 */
export function vibrateFeedback(type = 'light') {
  if (wx.canIUse('vibrateShort')) {
    if (type === 'heavy') {
      wx.vibrateLong()
    } else {
      wx.vibrateShort({
        type: type // light, medium, heavy
      })
    }
  }
}

/**
 * 显示操作反馈
 */
export function showActionSheet(itemList, itemColor = '#000000') {
  return new Promise((resolve, reject) => {
    wx.showActionSheet({
      itemList,
      itemColor,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 显示模态对话框
 */
export function showModal(options) {
  const defaultOptions = {
    title: '提示',
    showCancel: true,
    confirmText: '确定',
    cancelText: '取消'
  }
  
  return new Promise((resolve, reject) => {
    wx.showModal({
      ...defaultOptions,
      ...options,
      success: resolve,
      fail: reject
    })
  })
}

/**
 * 检查网络状态
 */
export function checkNetworkStatus() {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success: (res) => {
        resolve({
          isConnected: res.networkType !== 'none',
          networkType: res.networkType
        })
      },
      fail: reject
    })
  })
}

/**
 * 存储管理
 */
export const storage = {
  set(key, value, expire = null) {
    const data = {
      value,
      expire: expire ? Date.now() + expire : null
    }
    wx.setStorageSync(key, JSON.stringify(data))
  },
  
  get(key) {
    try {
      const dataStr = wx.getStorageSync(key)
      if (!dataStr) return null
      
      const data = JSON.parse(dataStr)
      
      // 检查是否过期
      if (data.expire && Date.now() > data.expire) {
        wx.removeStorageSync(key)
        return null
      }
      
      return data.value
    } catch (error) {
      return null
    }
  },
  
  remove(key) {
    wx.removeStorageSync(key)
  },
  
  clear() {
    wx.clearStorageSync()
  }
}